import json
import struct

from Lib import Utils


class MessageEvent:
    def __init__(self, data, header=None):
        if header is None:
            header = {}
        self.header = {**{}, **header}
        self.data = data
        self.send_time = Utils.NowTime()

    def ToJson(self):
        return {
                "header"   : self.header,
                "send_time": self.send_time,
                "data"     : self.data
        }

    def ToString(self):
        return json.dumps(self.ToJson()).encode('utf-8')

    def ToBytes(self):
        return bytes(self.ToString())


class MessageSync:
    def __init__(self, data, header=None):
        if header is None:
            header = {}
        self.header = {**{}, **header}
        self.data = data
        self.send_time = Utils.NowTime()

    def ToJson(self):
        return {
                "send_time": self.send_time,
                "header"   : self.header,
                "data"     : self.data
        }

    def ToString(self):
        return json.dumps(self.ToJson())

    def ToByte(self):
        return bytes(self.ToString(), encoding='utf-8')

    def Pack(self):
        return struct.pack(bytes, self.ToByte())
